var express = require('express');
var router = express.Router();
var express = require('express');
var formidable=require('formidable');
const fs = require('fs');
var sqlTool=require('../../models/sqlTool');

/* GET home page. */
var cacheFolder = 'public/images/upload/';
router.post('/api/material/upload/picture',function(req,res,next){
  //var currentUser = {id:1};
  //var userDirPath =cacheFolder+ currentUser.id;
  console.log(req.params);
  if(req.body.nowimg){
    var delimg='public'+req.body.nowimg;
    fs.unlinkSync(delimg);
  }
  if (!fs.existsSync(cacheFolder)) {
    fs.mkdirSync(cacheFolder);
  }
  var form = new formidable.IncomingForm(); //创建上传表单
  form.encoding = 'utf-8'; //设置编辑
  form.uploadDir = cacheFolder; //设置上传目录
  form.keepExtensions = true; //保留后缀
  form.maxFieldsSize = 2 * 1024 * 1024; //文件大小
  form.type = true;
  var displayUrl;
  form.parse(req, function(err, fields, files) {
    if (err) {
      res.send(err);
      return;
    }
    var extName = ''; //后缀名
    switch (files.upload.type) {
      case 'image/pjpeg':
        extName = 'jpg';
        break;
      case 'image/jpeg':
        extName = 'jpg';
        break;
      case 'image/png':
        extName = 'png';
        break;
      case 'image/x-png':
        extName = 'png';
        break;
    }
    if (extName.length === 0) {
      res.send({
        code: 202,
        msg: '只支持png和jpg格式图片'
      });
      return;
    } else {
      var avatarName = '/' + Date.now() + '.' + extName;
      var newPath = form.uploadDir + avatarName;
      fs.renameSync(files.upload.path, newPath); //重命名
      displayUrl=newPath;
      if(fields.nowImg){
        var delImg='public'+fields.nowImg;
        fs.unlink(delImg, function(err){
          if (err) console.log(err);
          console.log('successfully deleted /tmp/hello');
        });
      }
      res.send({
        code: 200,
        msg: '上传成功',
        url:displayUrl
      });
    }
  });
});
module.exports = router;
